
package biblio.service.reader;


import biblio.dao.ReaderDAO;
import biblio.domain.Reader;
import biblio.util.SourceName;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * Autocomplete for reader searched by last name.
 * @author mephisto
 */
@ManagedBean
@RequestScoped
public class AutocompleteReader 
{
    @PostConstruct
    public void init()
    {
        autocompleteList = new ArrayList<String>();
        ReaderDAO categoryDAO = (ReaderDAO)appContext.getBean("readerDAO");
        readers = categoryDAO.selectAll();
        for (Reader r : readers)
            autocompleteList.add(r.getId() + "-" + r.getLastName() + " " + r.getFirstName());
    }

    public List<String> autocomplete(String prefix)
    {
        List<String> result = new ArrayList<String>();
        if ((prefix == null) || (prefix.length() == 0))
        {
            for (int i = 0; i < 10; i++) 
                result.add(readers.get(i).getId() + "-" + readers.get(i).getLastName() + " " + readers.get(i).getFirstName());
        }
        else
        {
            Iterator<Reader> iterator = readers.iterator();
            while (iterator.hasNext())
            {
                Reader elem = ((Reader) iterator.next());
                if ((elem.getLastName() != null && elem.getLastName().toLowerCase().indexOf(prefix.toLowerCase()) == 0)
                    || "".equals(prefix)) 
                    result.add(elem.getId() + "-" + elem.getLastName() + " " + elem.getFirstName());
            }
        }

        return result;
    }

    public String getValue()
    {
        return value;
    }

    public void setValue(String value)
    {
        this.value = value;
    }
    
    public List<String> getAutocompleteList() 
    {
        return autocompleteList;
    }

    public void setAutocompleteList(List<String> autocompleteList) 
    {
        this.autocompleteList = autocompleteList;
    }

    public void setReaders(List<Reader> readers)
    {
        this.readers = readers;
    }

    public List<Reader> getReaders()
    {
        return readers;
    }
    

    static
    {
        appContext = new ClassPathXmlApplicationContext( new String[] {
                SourceName.DAO_APPLICATION_CONTEXT
        });
    }


    private static ApplicationContext appContext;
    private static Logger log = Logger.getLogger(AutocompleteReader.class);
    private List<String> autocompleteList;
    private List<Reader> readers;
    private String value;
}
